package top.yxqz.servlet;

import top.yxqz.school.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author Mr.余
 * @date 2022/11/7
 * @package top.yxqz.servlet
 *
 * 注册的servlet
 */
public class RegisterServletDemo extends HttpServlet {
    public static ArrayList<Student> students  = new ArrayList<>();
    int id = 0;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        获取前端表单信息.getParameter
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String agestr = request.getParameter("age");
        int age = Integer.parseInt(agestr); //将字符串转换成int
//        每次id自增
        id ++;
//        创建了学生对象，用来存储从前端传来的表单数据
        Student student = new Student(username,id,age,password);

        int res  =  repeat(student);
        if (res>0){
            System.out.println("该数据存在");
        }else {
            //       集合存值
            students.add(student);
            response.getWriter().print("注册成功，请你去登录吧");
        }
//        每次注册都打印集合中的所有对象信息
        System.out.println("-------------最新注册的结果---------------------");
        for (Student stu:students
             ) {
            System.out.println(stu);
        }
    }

    /**
     * 处理重复问题
     * @param student
     * @return
     */
    private int  repeat(Student student) {
        int number  = 0;
        for (Student stu:students
        ) {
            if (   stu.getName().equals(student.getName()))
            return  number  = 1;
        }
       return number  = -1;
    }
}
